import React, { useEffect, useRef, useState } from 'react'
import Icon from '@/components/Icon'
import { NavBar, Input } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import { RootState } from '@/types/store'
import io, { Socket } from 'socket.io-client'
import { getToken } from '@/utils/storage'

const Chat = () => {
  const history = useHistory()
  const userPhoto = useSelector((state: RootState) => state.profile.user.photo)
  const [messageList, setMessageList] = React.useState<
    {
      type: 'robot' | 'user'
      text: string
    }[]
  >([{ type: 'robot', text: '小智在此!' }, { type: 'user', text: '你好' }])
  // 用于缓存 socket.io 客户端实例
  const clientRef = useRef<Socket | null>(null)
  useEffect(() => {
    const client = io('http://toutiao.itheima.net', {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getToken().token
      }
    })
    client.on('message', (data) => {
      console.log('>>>>收到 socket.io 消息:', data)
      // 向聊天记录中添加一条消息
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', text: data.msg }
      ])
    })

    // 将客户端实例缓存到 ref 引用中
    clientRef.current = client

    // 在组件销毁时关闭 socket.io 的连接
    return () => {
      client.close()
    }
  }, [])
  // 输入框中的内容
  const [message, setMessage] = useState('')
  // 按发送消息
  const onSendMessage = (e: any) => {
    if (e.key === 'Enter') {
      if (message.trim() === '') {
        return
      }
      // 1. 发消息
      clientRef.current!.emit('message', {
        msg: message,
        timestamp: Date.now()
      })
      // 2. 添加到聊天记录
      setMessageList([...messageList, { type: 'user', text: message }])

      // 3. 清空
      setMessage('')
    }
  }
  // 用于操作聊天列表元素的引用
  const chatListRef = useRef<HTMLDivElement>(null)
  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(
    () => {
      const current = chatListRef.current!
      current.scrollTop = current.scrollHeight
    },
    [messageList]
  )
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={chatListRef}>
        {messageList.map((msg, index) => {
          if (msg.type === 'robot') {
            /* 机器人的消息 */
            return (
              <div className="chat-item" key={index}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{msg.text}</div>
              </div>
            )
          } else {
            /* 用户的消息 */
            return (
              <div className="chat-item user" key={index}>
                <img src={userPhoto} alt="" />
                <div className="message">{msg.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          value={message}
          onChange={(e) => setMessage(e)}
          onKeyUp={onSendMessage}
          className="no-border"
          placeholder="请描述您的问题"
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
